var express = require('express');
var router = express.Router();
const { UserModel } = require('../db/index')
const Op = require('sequelize').Op

/* GET users listing. */
router.post('/get', async (req, res, next) => {
  const { page = 1, pageSize = 10, id } = req.body
  if (page < 1) {
    page = 1
  }
  let whereOption = {}
  if (id) {
    whereOption.id = id
  }
  const users = await UserModel.findAll({
    limit: pageSize,
    offset: (page - 1) * pageSize,
    where: whereOption
  })
  const total = await UserModel.findAll()
  res.status(200).json({
    code: 200,
    data: users,
    total: total.length
  })
});
router.post("/login", async (req, res, next) => {
  const { username, password } = req.body
  const whereOption = {
    username
   }
   const result = await UserModel.findOne({
     where: whereOption
   })
   if (result === null) {
    res.json({
      code: 500,
      msg: '用户不存在'
    })
   } else {
    if (password === result.password) {
      res.json({
        code: 200,
        data: result
      })
    } else {
      res.json({
        code: 500,
        msg: '密码不正确'
      })
    }
   }
});
router.post("/register", async function (req, res, next) {
  const { username, password, roles } = req.body
  const whereOption = {
    username
   }
  const result = await UserModel.findOne({
    where: whereOption
  })
  if (result) {
    res.json({
      code: 500,
      msg: '用户名已存在'
    })
  } else {
    const rs = await UserModel.create(req.body)
    res.json({
      code: 200,
      data: rs
    })
  }
});
router.post("/update/:id", async function (req, res, next) {
  console.log(req.params.id)
  const whereOption = {}
  if (req.params.id) {
    whereOption.id = req.params.id
  }
  const result = await UserModel.update(req.body, {
    where: whereOption
  })
  res.json({
    code: 200
  })
});
router.post("/delete/:id", async function (req, res, next) {
  console.log(req.params.id)
  const result = await UserModel.destroy({
    where: {
      id: req.params.id
    }
  })
  res.json({
    code: 200
  })
});

module.exports = router;
